/**
 * 通用js方法封装处理
 * 包旭慧 24/4/24
 */
import { Loading, Message } from 'element-ui'
import dayjs from 'dayjs'
import axios from 'axios'
import { getToken } from '@/utils/publicUtils/auth'
let loading
var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1)

/**
 * 获取当前日期和星期几
 */
export function getTodayTime() {
  const time = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const weekDay = dayjs().day()
  switch (weekDay) {
    case 1:
      return time + '星期一'
    case 2:
      return time + ' 星期二'
    case 3:
      return time + ' 星期三'
    case 4:
      return time + ' 星期四'
    case 5:
      return time + ' 星期五'
    case 6:
      return time + ' 星期六'
    case 7:
      return time + ' 星期日'
    default:
      return time
  }
}

/**
 * @description: 日期格式化
 * @Author: baoxuhui
 * @param {*} time//转换的值
 * @param {*} pattern//传值格式  默认{y}-{m}-{d} {h}:{i}
 * @return {*}
 */
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}'
  // const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      if (time.length === 4) {
        // 处理火狐浏览器对 new Date()必须为年月日的格式
        time = time + '/01' + '/01'
      }
      if (time.length === 7) {
        // 处理火狐浏览器对 new Date()必须为年月日的格式
        time = time + '/01'
      }
      // time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
      if (time.length === 4) {
        // 处理火狐浏览器对 new Date()必须为年月日的格式
        time = time + '/01' + '/01'
      }
      if (time.length === 7) {
        // 处理火狐浏览器对 new Date()必须为年月日的格式
        time = time + '/01'
      }
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // console.log(result)
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

/**
 * @description: 当前日期
 * @Author: baoxuhui
 * @param {*} type 转换的类型  年：year，月：month，日：date，年-月：year-month，年-月-日：year-month-date，月-日：month-date，时：hh，分：mf，秒：ss，时-分：hh-mf，时-分-秒:hh-mf-ss，星期几：week  不传时默认时间到秒
 * @return {*}
 */
export function getTimeDate(type) {
  var that = this
  var vWeek = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  var getDay = new Date().getDay()
  const yy = new Date().getFullYear()
  var mm =
        new Date().getMonth() < 10
          ? '0' + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1
  var dd =
        new Date().getDate() < 10
          ? '0' + new Date().getDate()
          : new Date().getDate()
  const hh = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()

  const mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
  const ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
  if (type === 'year') {
    that.gettime = yy
  } else if (type === 'month') {
    that.gettime = mm
  } else if (type === 'date') {
    that.gettime = dd
  } else if (type === 'year-month') {
    that.gettime = yy + '-' + mm
  } else if (type === 'year-month-date') {
    that.gettime = yy + '-' + mm + '-' + dd
  } else if (type === 'month-date') {
    that.gettime = mm + '-' + dd
  } else if (type === 'week') {
    that.gettime = vWeek[getDay]
  } else if (type === 'hh') {
    that.gettime = hh
  } else if (type === 'mf') {
    that.gettime = mf
  } else if (type === 'ss') {
    that.gettime = ss
  } else if (type === 'hh-mf') {
    that.gettime = hh + ':' + mf
  } else if (type === 'hh-mf-ss') {
    that.gettime = hh + ':' + mf + ':' + ss
  } else {
    that.gettime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
  }

  return that.gettime
}
/**
 * @description: 表单重置
 * @Author: baoxuhui
 * @param {*} refName//表单名
 * @return {*}
 */
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}
/**
 * @description: 表单字段进行校验
 * @Author: baoxuhui
 * @param {*} refName//表单名
 * @param {*} key//需通过验证的Key
 * @return {*}
 */
export function validateFormField(refName, key) {
  if (this.$refs[refName]) {
    this.$nextTick(() => {
      this.$refs[refName].validateField(key)
    })
  }
}

/**
 * @description: // 回显数据字典
 * @Author: baoxuhui
 * @param {*} datas//数组
 * @param {*} value//转换的值
 * @return {*}
 */
export function selectDictLabel(datas, value) {
  var actions = []
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue === '' + value) {
      actions.push(datas[key].dictLabel)
      return true
    }
  })
  return actions.join('')
}

/**
 * @description: // 回显数据字典（字符串数组）
 * @Author: baoxuhui
 * @param {*} datas//数组
 * @param {*} value//转换的值
 * @param {*} separator//返回字符串的隔开符
 * @return {*}
 */
export function selectDictLabels(datas, value, separator) {
  var actions = []
  var currentSeparator = undefined === separator ? ',' : separator
  var temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue === '' + temp[val]) {
        actions.push(datas[key].dictLabel + currentSeparator)
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

/**
 * @description: // 数组格式转字符串
 * @Author: baoxuhui
 * @param {*} data 数组
 * @param {*} objName 需分割目标对象
 * @param {*} separator 分隔符
 * @return {*}
 */
export function arrayToString(data, objName, separator) {
  var actions = []
  if (data && data.length != 0) {
    var currentSeparator = undefined === separator ? ',' : separator
    data.forEach((item, index) => {
      if(item[objName]){
        actions.push(item[objName])
      }
    })
  }
  return actions.join(currentSeparator)
}


// 原有通用下载方法
export function download(fileName) {
  window.location.href = baseURL + '/common/download?fileName=' + encodeURI(fileName) + '&delete=' + true
}

/**
 * @description: // 转换字符串，undefined,null等转化为""
 * @Author: baoxuhui
 * @param {*} value//转换的值
 * @return {*}
 */
export function praseStrEmpty(value) {
  if (!value || value === 'undefined' || value === 'null') {
    return ''
  }
  return value
}
/**
 * @description: 判空
 * @Author: baoxuhui
 * @param {*} value//判断值
 * @return {*}
 */
export function sentencedEmpty(value) {
  if (value !== undefined && value !== '' && value !== null) {
    return true
  }
}

/**
 * base64编码
 * @param {*} str
 */
export function base64encode(str) {
  var out, i, len
  var c1, c2, c3
  len = str.length
  i = 0
  out = ''
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff
    if (i == len) {
      out += base64EncodeChars.charAt(c1 >> 2)
      out += base64EncodeChars.charAt((c1 & 0x3) << 4)
      out += '=='
      break
    }
    c2 = str.charCodeAt(i++)
    if (i == len) {
      out += base64EncodeChars.charAt(c1 >> 2)
      out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
      out += base64EncodeChars.charAt((c2 & 0xF) << 2)
      out += '='
      break
    }
    c3 = str.charCodeAt(i++)
    out += base64EncodeChars.charAt(c1 >> 2)
    out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
    out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6))
    out += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return out
}
/**
 * base64解码
 * @param {*} str
 */
export function base64decode(str) {
  var c1, c2, c3, c4
  var i, len, out
  len = str.length
  i = 0
  out = ''
  while (i < len) {
    /* c1 */
    do {
      c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
    }
    while (i < len && c1 == -1)
    if (c1 == -1) { break }
    /* c2 */
    do {
      c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]
    }
    while (i < len && c2 == -1)
    if (c2 == -1) { break }
    out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4))
    /* c3 */
    do {
      c3 = str.charCodeAt(i++) & 0xff
      if (c3 == 61) { return out }
      c3 = base64DecodeChars[c3]
    }
    while (i < len && c3 == -1)
    if (c3 == -1) { break }
    out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2))
    /* c4 */
    do {
      c4 = str.charCodeAt(i++) & 0xff
      if (c4 == 61) { return out }
      c4 = base64DecodeChars[c4]
    }
    while (i < len && c4 == -1)
    if (c4 == -1) { break }
    out += String.fromCharCode(((c3 & 0x03) << 6) | c4)
  }
  return out
}
/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data, id, parentId, children, rootId) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId =
        rootId ||
        Math.min.apply(
          Math,
          data.map((item) => {
            return item[parentId]
          })
        ) ||
        0
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  // 循环所有项
  const treeData = cloneData.filter((father) => {
    const branchArr = cloneData.filter((child) => {
      // 返回每一项的子级数组
      return father[id] === child[parentId]
    })
    branchArr.length > 0 ? (father.children = branchArr) : ''
    // 返回第一层
    return father[parentId] === rootId
  })
  return treeData != '' ? treeData : data
}
/**
 * @description: number类型的输入框获取光标
 * @Author: baoxuhui
 * @param {*} e
 * @return {*}
 */
export function focusNumBerFun(e) {
  const value = e.target.value
  if (value === '' || value === undefined || value === null || value === 0 || value === '0') {
    e.target.value = null
  } else {
    e.target.value = Number(e.target.value)
  }
  // if (e.target.value === '' || e.target.value === undefined || e.target.value === null || e.target.value === 0 || e.target.value === '0' || e.target.value === '0.00') {
  //   e.target.value = ''
  // } else {
  //   e.target.value = Number(e.target.value)
  // }
}
/**
 * @description: number类型的输入框失去光标
 * @Author: baoxuhui
 * @param {*} e//限制的值
 * @param {*} objName//数据来源的对象
 * @param {*} valName//数据来源Key
 * @param {*} fixd//保留小数点位数 默认：0
* @param {*} advancedQuery//是否为查询条件  默认：'',有值：advancedQuery
* @param {*} item//查询条件转换的对象
* @param {*} max//查询条件转换的对象中的key
 * @return {*}
 */
export function blurNumBerFun(e, numFixd,row,valName) {
  // console.log(e)
  const value = e.target.value
  //   if (isNaN(value) == true) {
  //     row[valName] = null
  //   }
  if (numFixd > 0) {
    if (Number(value) > 0) {
        row[valName] = Number(value).toFixed(numFixd)
    }
  } else {
    if (Number(value) > 0) {
        row[valName] = Number(value).toFixed(numFixd)
    }
  }
  return row
}
/**
 * @description: 数字输入框的限制
 * @Author: baoxuhui
 * @param {*} value//限制的值
 * @param {*} objName//数据来源的对象
 * @param {*} valName//数据来源Key
 * @param {*} min//可输入的字符串最小值 默认:0
* @param {*} max//可输入的字符串最大值   默认:1000000000
* @param {*} advancedQuery//是否为查询条件  默认：'',有值：advancedQuery
* @param {*} item//查询条件转换的对象
* @param {*} max//查询条件转换的对象中的key
 * @return {*}
 */
export function numberInput(value, objName, valName, min, max, advancedQuery, item, itemKey) {
  if (isNaN(value)) {
    value = null
  }
  if (!this.sentencedEmpty(value)) {
    value = ''
  }
  // console.log(value)
  let minValue = 0// 最小值（默认初始值）
  let maxValue = 1000000000// 最大值（默认初始值）
  if (this.sentencedEmpty(max)) {
    maxValue = max
  }
  if (this.sentencedEmpty(min)) {
    minValue = min
  }

  let newValue = value
  if (newValue < 0) {
    if (minValue >= 0) {
      newValue = 0
    }
    if (minValue < 0 && newValue <= minValue) {
      newValue = minValue
    }
  }
  if (newValue >= maxValue) {
    newValue = maxValue
  }
  objName[valName] = newValue
  // 高级查询特殊处理
  if (this.sentencedEmpty(advancedQuery)) {
    item[itemKey] = newValue
  }
}

/**
 * @description: 数字输入框的限制--经纬度设置
 * @Author: baoxuhui
 * @param {*} value//限制的值
 * @param {*} objName//数据来源的对象
 * @param {*} valName//数据来源Key
 * @param {*} min//可输入的字符串最小值 默认:0
 * @param {*} max//可输入的字符串最大值   默认:1000000000
 * @param {*} advancedQuery//是否为查询条件  默认：'',有值：advancedQuery
 * @param {*} item//查询条件转换的对象
 * @param {*} max//查询条件转换的对象中的key
 * @return {*}
 */
export function numberInputGeo(value, objName, valName, min, max, advancedQuery, item, itemKey) {
  if (isNaN(value)) {
    value = parseFloat(value)
  }
  if (!this.sentencedEmpty(value)) {
    value = ''
  }
  let minValue = 0 // 最小值（默认初始值）
  let maxValue = 1000000000// 最大值（默认初始值）
  if (this.sentencedEmpty(max)) {
    maxValue = max
  }
  if (this.sentencedEmpty(min)) {
    minValue = min
  }

  let newValue = value
  if (newValue < 0) {
    if (minValue >= 0) {
      newValue = 0
    }
    if (minValue < 0 && newValue <= minValue) {
      newValue = minValue
    }
  } else {
    if (newValue >= maxValue) {
      newValue = maxValue
    } else {
      if (newValue.indexOf('.') !== -1) {
        let newParts
        const oldParts = newValue.split('.')
        if (oldParts[1]) {
          if (oldParts[1].length > 13) {
            newParts = oldParts[1].slice(0, 13)
            newValue = oldParts[0] + '.' + newParts
          } else {
            newParts = oldParts[1]
            newValue = oldParts[0] + '.' + newParts
          }
        }
      }
    }
  }

  objName[valName] = newValue
  // 高级查询特殊处理
  if (this.sentencedEmpty(advancedQuery)) {
    item[itemKey] = newValue
  }
}

/**
 * @description: 千分位
 * @Author: baoxuhui
 * @param {*} number//转换的值
 * @param {*} decimals//保留小数点位数
 * @param {*} decPoint//小数点标记
 * @param {*} thousandsSep//千分位的隔开标记
 * @param {*} roundtag//四舍五入
 * @return {*}
 */
export function numberFormat(number, decimals, decPoint, thousandsSep, roundtag) {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  roundtag = roundtag || 'ceil' // 'ceil','floor','round'
  var n = !isFinite(+number) ? 0 : +number
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  var s = ''
  var toFixedFix = function(n, prec) {
    var k = Math.pow(10, prec)
    return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  var re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}
/**
 * @description: 数字转换大写金额
 * @Author: baoxuhui
 * @param {*} money//
 * @return {*}
 */
export function toChineseNum(money) {
  var cnNums = new Array(
    '零',
    '壹',
    '贰',
    '叁',
    '肆',
    '伍',
    '陆',
    '柒',
    '捌',
    '玖'
  )
  // 基本单位
  var cnIntRadice = new Array('', '拾', '佰', '仟')
  // 对应整数部分扩展单位
  var cnIntUnits = new Array('', '万', '亿', '兆')
  // 对应小数部分单位
  var cnDecUnits = new Array('角', '分', '毫', '厘')
  // 整数金额时后面跟的字符
  var cnInteger = '整'
  // 整型完以后的单位
  var cnIntLast = '元'
  // 最大处理的数字
  var maxNum = 999999999999999.9999
  // 金额整数部分
  var integerNum
  // 金额小数部分
  var decimalNum
  // 输出的中文金额字符串
  var chineseStr = ''
  // 分离金额后用的数组，预定义
  var parts
  if (money == '' && money == null && money == undefined) {
    return '零元整'
  }
  money = parseFloat(money)
  if (money >= maxNum) {
    // 超出最大处理数字
    return '零元整'
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转换为字符串
  money = money.toString()
  if (money.indexOf('.') == -1) {
    integerNum = money
    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0
    var IntLen = integerNum.length
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1)
      var p = IntLen - i - 1
      var q = p / 4
      var m = p % 4
      if (n == '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1)
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum == '') {
    chineseStr += cnInteger
  }
  return chineseStr
}
/**
 * @description 数字转文字 万级
 * @author: 张佳敏
 * @param num 数字
 * @return {*}
 */
export function toChinesNum(num) {
  const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'] // changeNum[0] = "零"
  const unit = ['', '十', '百', '千', '万']
  num = parseInt(num)
  const getWan = (temp) => {
    const strArr = temp.toString().split('').reverse()
    let newNum = ''
    for (var i = 0; i < strArr.length; i++) {
      newNum = (i == 0 && strArr[i] == 0 ? '' : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? '' : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum
    }
    return newNum
  }
  const overWan = Math.floor(num / 10000)
  let noWan = num % 10000
  if (noWan.toString().length < 4) noWan = '0' + noWan
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}

/**
 * @description: // 全局loading
 * @Author: baoxuhui
 * @param {*} text//提示语
 * @return {*}
 */
export function startLoading(text) {
  loading = Loading.service({
    lock: true,
    text: text,
    background: 'rgba(255, 255, 255, 0.7)'
  })
}
/**
 * @description: // 移除loading
 * @Author: baoxuhui
 * @return {*}
 */
export function closeLoading() {
  loading.close()
}

/**
 * @description: 消息提示
 * @Author: 张佳敏
 * @param {*} msg // 消息文字
 * @param {*} showClose // 是否显示关闭按钮
 * @param {*} type // 主题 成功:success /警告:warning/ 默认:info / 错误:error
 * @return {*}
 */
export function msgAlt(msg, type, showClose = true) {
  Message({ message: msg, type: type, showClose: showClose })
}

/**
 * @description: // 页数展示
 * @Author: baoxuhui
 * @param {*} index //第几页数
 * @param {*} pagetion //每页显示数
 * @return {*}
 */
export function pageIndex(index, pagetion) {
  if (pagetion.pageSize === undefined && pagetion.pageNum === undefined) {
    return Number(pagetion.page - 1) * Number(pagetion.size) + Number(index) + 1
  } else {
    return Number(pagetion.pageNum - 1) * Number(pagetion.pageSize) + Number(index) + 1
  }
}
/**
 * @description: 百分比%
 * @Author: baoxuhui
 * @param {*} numerator//分子
 * @param {*} denominator//分母
 * @return {*}
 */
export function mathRound(numerator, denominator) {
  if (Number(numerator) > 0 && Number(denominator) > 0) {
    const mathRound = Math.round(Number(numerator) / Number(denominator) * 10000) / 100
    return mathRound.toFixed(2) + '%'
  } else {
    return '0.00%'
  }
}

/**
 * @description: 小数点转
 * @author: baoxuhui
 * @param {*} value 值
 * @param {*} numFixd 小数点后几位
 * @return {*}
 */
export function decimalRound(value, numFixd) {
  if (Number(value) > 0) {
    return Number(value).toFixed(numFixd)
  } else {
    return '0.00'
  }
}
/**
 * @description: // 转附件路径(后端文件路径加密后需要token来请求文件)
 * @Author: baoxuhui
 * @param {*} path//文件路径
 * @return {*}
 */
export function returnPath(path) {
  return new Promise(resolve => {
    return axios({
      method: 'get',
      url: path,
      responseType: 'blob',
      headers: { 'x-auth-token': getToken() }
    }).then(res => {
      // var blob = new Blob([res.data], { type: res.data.type })
      resolve(URL.createObjectURL(res.data))
      // return URL.createObjectURL(res.data)
      // return/
    })
  })
}
/**
 * @description: 数组对象去重
 * @Author: baoxuhui
 * @param {*} param  数组对象格式的数据 [{key:value},{key:value},{key:value}]
 * @param {*} key 筛选数组对象唯一值的key 一般是id
 * @return {*[]} 返回一个不重复的值
 */
export function arrayObjectDeDuplication(param, key) {
  const map = new Map()
  let result = []
  for (const item of param) {
    if (!map.has(param[key])) {
      result = map.set(item[key], item)
    }
  }
  return [...result.values()]
}
/**
 * @description: 两个对象数组做比对
 * @Author: baoxuhui
 * @param {*} objArr1//数组1
 * @param {*} objArr2//数组2
 * @param {*} key//作对比的key   key不传值默认为空
 * @param {*} type//返回值为相同/不相同 alike/unlike  type不传值默认为alike
 * @return {*}
 */
export function arrayObjectComparison(objArr1, objArr2, key, type) {
  const arrList = []
  // 有key(视为obj数组)
  if (sentencedEmpty(key)) {
    // 获取不相同
    if (type === 'unlike') {
      objArr1.forEach(element => {
        element.isExist = false
        objArr2.forEach(eleme => {
          if (element[key] === eleme[key]) {
            element.isExist = true
            return
          }
        })
        if (!element.isExist) {
          arrList.push(element)
        }
      })
    } else {
      objArr1.forEach(element => {
        objArr2.forEach(eleme => {
          console.log(element[key])
          if (element[key] === eleme[key]) {
            arrList.push(element)
          }
        })
      })
    }
    // 无key(视为常规数组)
  } else {
    // 获取不相同
    if (type === 'unlike') {
      objArr1.forEach(element => {
        element.isExist = false
        objArr2.forEach(eleme => {
          if (element === eleme) {
            element.isExist = true
            return
          }
        })
        if (!element.isExist) {
          arrList.push(element)
        }
      })
    } else {
      objArr1.forEach(element => {
        objArr2.forEach(eleme => {
          if (element === eleme) {
            arrList.push(element)
          }
        })
      })
    }
  }

  console.log(arrList)
  return arrList
}

/**
 * @description: // 时间组件区间取值规定
 * @Author: baoxuhui
 * @param {*} item//包含值的对象 obj
 * @param {*} type//开始时间：start,结束时间：end
 * @param {*} startLable//开始时间展示Lable
 * @param {*} startLableKey//开始时间在对象中的key
 * @param {*} endLable//结束时间展示Lable
 * @param {*} endLableKey//结束时间在对象中的key
 * @return {*}
 */
export function timeChangeFun(item, type, startLable, startLableKey, endLable, endLableKey) {
  const startTime = item[startLableKey]
  const endTime = item[endLableKey]
  if (type === 'start') {
    comptimeStart(startTime, endTime, startLable, startLableKey, endLable, endLableKey, item)
  } else {
    comptimeEnd(startTime, endTime, startLable, startLableKey, endLable, endLableKey, item)
  }
}
/**
 * @description: 开始时间判断
 * @Author: baoxuhui
 * @param {*} startTime//开始值
 * @param {*} endTime //结束值
 * @param {*} startLable//开始时间展示Lable
 * @param {*} startLableKey//开始时间在对象中的key
 * @param {*} endLable//结束时间展示Lable
 * @param {*} endLableKey//结束时间在对象中的key
 * @param {*} item//包含值的对象 obj
 * @return {*}
 */
export function comptimeStart(startTime, endTime, startLable, startLableKey, endLable, endLableKey, item) {
  if (endTime != null) {
    var a = (Date.parse(startTime) - Date.parse(endTime)) / 3600 / 1000
    if (a > 0) {
      msgAlt(startLable + '必须小于' + endLable, 'error')
      item[startLableKey] = null
      return item
    } else {
      return startTime
    }
  } else {
    return startTime
  }
}
/**
 * @description: 结束时间判断
 * @Author: baoxuhui
 * @param {*} startTime//开始值
 * @param {*} endTime //结束值
 * @param {*} startLable//开始时间展示Lable
 * @param {*} startLableKey//开始时间在对象中的key
 * @param {*} endLable//结束时间展示Lable
 * @param {*} endLableKey//结束时间在对象中的key
 * @param {*} item//包含值的对象 obj
 * @return {*}
 */
export function comptimeEnd(startTime, endTime, startLable, startLableKey, endLable, endLableKey, item) {
  if (startTime) {
    var a = (Date.parse(endTime) - Date.parse(startTime)) / 3600 / 1000
    if (a < 0) {
      msgAlt(endLable + '必须大于' + startLable, 'error')
      item[endLableKey] = null
      return item
    } else {
      return endTime
    }
  } else {
    msgAlt('请选择' + startLable, 'error')
  }
}

/**
 * 数组去重 删除前面 保留后面(最新)
 */
export function rrayUnique(arr, name) {
  const hash = {}
  return arr.reduce((acc, cru, index) => {
    if (!hash[cru[name]]) {
      hash[cru[name]] = {
        index: acc.length
      }
      acc.push(cru)
    } else {
      acc.splice(hash[cru[name]]['index'], 1, cru)
    }
    return acc
  }, [])
}

/**
 * 附件 判断是否含有汉字
 */
export function isChina(name) {
  var patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi
  if (!patrn.exec(name)) {
    return false
  } else {
    return true
  }
}

/**
 * 附件 判断是否含有汉字并处理返回内容
 */
export function isFileChinaNameBack(name) {
  if(name){
    if (isChina(name) == true) {
      name = decodeURI(percent2percent25(name)).replace('?baifenhao?', '%')
    } else {
      name = decodeURI(name)
    }
  } else {
    name = ''
  }
  return name
}

/**
 * 附件 %分号转 ?baifenhao?
 */
export function percent2percent25(URI) {
  if (URI.indexOf('%') > -1) {
    return URI.replace(/%/g, '?baifenhao?')
  } else {
    return URI
  }
}
/**
 * @description:  tabs权限(可在系统管理配置调取（按钮式配置）)
 * @Author: baoxuhui
 * @param {*} tabsList //tabs标签页数组
 * @return {*}
 */
export function tabsPermission(tabsList) {
  const newTabsList = JSON.parse(JSON.stringify(tabsList))
  const all_permission = '*:*:*'
  const permissions = this.$store.getters && this.$store.getters.permissions
  if (permissions.length !== 0) {
    newTabsList.forEach(element => {
      element.btnFlagBool = true
      if (this.sentencedEmpty(element.hasPermi)) {
        element.btnFlagBool = permissions.some(permission => {
          return all_permission === permission || (element.hasPermi === permission)
          // return all_permission === permission || element.hasPermi.includes(permission)
        })
      }
    })
    const someTabs = newTabsList.filter(item => item.btnFlagBool === true)
    return someTabs
  }
}
/**
 * @description:  特殊按钮权限(可在系统管理配置调取（按钮式配置）)
 * @Author: baoxuhui
 * @param {*} btnStr //tabs标签页数组
 * @return {*}
 */
export function btnPermission(btnStr) {
  // console.log(btnStr)
  let btnFlagBool = true
  const all_permission = '*:*:*'
  const permissions = this.$store.getters && this.$store.getters.permissions
  // console.log(permissions)
  if (permissions.length === 0) {
    btnFlagBool = false
  } else {
    btnFlagBool = permissions.some(permission => {
      return all_permission === permission || (btnStr === permission)
    })
  }
  // console.log(btnFlagBool)
  return btnFlagBool
}

/**
 * 由于 a 标签会导致 下载操作成为预览效果
 * 所以 判断那些后缀名需要单独处理 下载操作
 * @param {*} filename
 */
export function isImage(filename) {
  var ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
  return (
      ext === 'bmp' || ext === 'jpg' || ext === 'jpeg' || ext === 'png' || ext === 'tif' || ext === 'gif' ||
      ext === 'pcx' || ext === 'tga' || ext === 'exif' || ext === 'fpx' || ext === 'svg' || ext === 'psd' ||
      ext === 'cdr' || ext === 'pcd' || ext === 'dxf' || ext === 'ufo' || ext === 'eps' || ext === 'ai' ||
      ext === 'raw' || ext === 'WMF' || ext === 'webp' || ext === 'avif' || ext === 'apng' || ext === 'pdf' ||
      ext === 'txt' || ext === 'rtf' || ext === 'json'
  )
}
